package org.jflame.commons.json.fastjson2;

import org.jflame.commons.model.pair.IIntKeyPair;
import org.jflame.commons.model.pair.KeyValuePair;

import java.lang.reflect.Type;

import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.reader.ObjectReader;
import com.alibaba.fastjson2.writer.ObjectWriter;

public class IntKeyPairEnumCustomized {

    /**
     * IntKeyPair自定义序列化,只输出key值
     * 
     * @author charles.zhang
     */
    public static class IntKeyPairUsingKeySerializer implements ObjectWriter<IIntKeyPair> {

        @Override
        public void write(JSONWriter jsonWriter, Object object, Object fieldName, Type fieldType, long features) {
            if (object == null) {
                jsonWriter.writeNull();
                return;
            }

            IIntKeyPair pair = (IIntKeyPair) object;
            jsonWriter.writeString(pair.getKey());
        }

    }

    /**
     * 实现了IntKeyPair接口的枚举类的自定义反序列化. 通过key值生成相应枚举类
     * 
     * @author charles.zhang
     */
    public static class IntKeyPairEnumDeserializer<T extends Enum<T> & IIntKeyPair> implements ObjectReader<T> {

        @SuppressWarnings("unchecked")
        @Override
        public T readObject(JSONReader jsonReader, Type fieldType, Object fieldName, long features) {
            if (jsonReader.nextIfNull()) {
                return null;
            }
            return KeyValuePair.getEnumByKey((Class<T>) fieldType, jsonReader.readInt32());
        }
    }
}
